package cn.flant.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

	public static long ip32ToLong(String ip) {
		Matcher m = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})").matcher(ip);
		long value = 0;
		if (m.find()) {
			for (int i = 1; i <= m.groupCount(); i++) {
				int t = Integer.valueOf(m.group(i));
				value = value << 8;
				value += t;
			}
		} else {
			value = -1;
		}
		return value;
	}

	public static String longToIp32(long value) {
		String ip = null;
		for (int i = 0; i < 4; i++) {
			long v = value % ((long) Math.pow(2, (i + 1) * 8)) >> i * 8;
			ip = ip == null ? String.valueOf(v) : (String.valueOf(v) + "." + ip);
		}
		return ip;
	}

	public static String escapeCharacter(String c) {
		if (c.equals("<")) {
			return "&lt;";
		} else if (c.equals(">")) {
			return "&gt;";
		} else if (c.equals("&")) {
			return "&amp;";
		} else if (c.equals("\"")) {
			return "&quot;";
		} else if (c.equals("'")) {
			return "&apos;";
		}
		return c;
	}
	
	public static void main(String[] args) {
		long value = Util.ip32ToLong("222.223.155.48");
		System.out.println(value);
		System.out.println(Util.longToIp32(value));
	}

}
